const app = new Vue({
    el: '#app',
    data() {
        return {
            access_token: '',
            loginDialogVisible: false,
            loginForm: {
                user_name: '',
                password: '',
            },
            loginRules: {
                user_name: [{required: true, message: '登录名不能为空', trigger: 'blur'}],
                password: [{required: true, message: '密码不能为空', trigger: 'blur'}],
            },
            registerDialogVisible: false,
            registerForm: {
                user_name: '',
                password: '',
            },
            registerRules: {
                user_name: [{required: true, message: '登录名不能为空', trigger: 'blur'}],
                password: [{required: true, message: '密码不能为空', trigger: 'blur'}],
            },
            chatRoomDialogVisible: false,
            lock: false,
            webSocket: null,
            message: '',
            connectStatus: '',
            applyList: [],
            friendName: '',
            friendList: [],
            userInfo: [],
            handleMessage: '',
        }
    },
    methods: {
        init() {
            this.getApiToken();
            if (this.access_token !== null) { // 已登录
                this.getUserInfo();
                this.getFriendList(this.link);
            } else {
                // 打开登录页面
                this.loginDialogVisible = true;
            }
        },
        getApiToken() {
            this.access_token = localStorage.getItem('access_token');
        },
        setApiToken(access_token) {
            localStorage.setItem('access_token', access_token);
        },
        delApiToken() {
            localStorage.removeItem('access_token');
            localStorage.removeItem('userInfo');
        },
        toLogin() {
            this.registerForm = {};
            this.registerDialogVisible = false;
            this.loginDialogVisible = true;
        },
        login(formName) {
            let _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    axios.post('/api/user/login', this.loginForm).then(res => {
                        if (res.data.code === 1) {
                            this.$message.error(res.data.message);
                            return false;
                        }

                        this.setApiToken(res.data.content.access_token);
                        this.loginDialogVisible = false;
                        this.$message.success({
                            message: res.data.message,
                            onClose: function () {
                                _this.init()
                            },
                        });
                        return false;
                    }).catch(error => {
                        this.$message.error(error.message);
                        return false;
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        toRegister() {
            this.loginForm = {};
            this.loginDialogVisible = false;
            this.registerDialogVisible = true;
        },
        register(formName) {
            let _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    axios.post('/api/user/register', this.registerForm).then(res => {
                        if (res.data.code === 1) {
                            this.$message.error(res.data.message);
                            return false;
                        }

                        this.registerDialogVisible = false;
                        this.$message.success({
                            message: res.data.message,
                            onClose: function () {
                                _this.init()
                            },
                        });
                        return false;
                    }).catch(error => {
                        this.$message.error(error.message);
                        return false;
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        logout() {
            let _this = this;
            axios.post('/api/user/logout', {
                access_token: this.access_token
            }).then(res => {
                if (res.data.code === 1) {
                    this.$message.error(res.data.message);
                    return false;
                }

                this.loginForm = {
                    user_name: '',
                    password: '',
                };
                this.delApiToken();

                this.$message.success({
                    message: res.data.message,
                    onClose: function () {
                        _this.init();
                    },
                });
            }).catch(error => {
                this.$message.error(error.message);
                return false;
            });
        },
        link() {
            let _this = this;
            let wsServer = 'ws://127.0.0.1:9502?type=index&access_token=' + this.access_token;
            let webSocket = new WebSocket(wsServer);

            webSocket.onopen = function (res) {
                _this.connectStatus = '连接成功，欢迎！';
            };

            webSocket.onmessage = function (res) {
                let data = JSON.parse(res.data)['data'];
                console.log('onmessage:', data)
                switch (data['type']) {
                    case 'addFriend':
                        _this.renderApplyList(data);
                        break;
                    case 'handleFriend':
                        _this.renderFriend(data);
                        break;
                    case 'chat':
                        _this.renderDelay(data);
                }

            };

            webSocket.onclose = function (res) {
                _this.connectStatus = '连接关闭！';
                webSocket.close();
                _this.relink();
            };

            webSocket.onerror = function (res, e) {
                webSocket.close();
                _this.relink();
            };

            this.webSocket = webSocket;
        },
        renderApplyList(data) {
            let message = data['message'] ? data['message'] : '对方没有任何留言';
            this.applyList.push({user_name: data.user_name, message: message, from: data.from});
        },
        renderFriend(data) {
            this.handleMessage = data['user_name'] + ' ' + data['message'];
            if(data['desc'] === 1) {
                this.getFriendList();
            }
        },
        renderDelay(data) {
            if(data['count'] !== 0) {
                this.friendList.forEach((item, index) => {
                    item.count = 0;
                    item.message = '';
                    if(data['uid'] === item.id) {
                        item.count = data['count']
                        item.message = data['message'];
                    }
                });
            }

            console.log('renderDelay: ', data, this.friendList)
            this.$forceUpdate(); // 强制刷新
        },
        addFriend() {
            axios.post('/api/user/addFriend', {
                access_token: this.access_token,
                user_name: this.friendName,
                message: '',
            }).then(res => {
                if (res.data.code === 1) {
                    this.$message.error(res.data.message);
                    return false;
                }

                this.$message.success(res.data.message);
                return false;
            }).catch(error => {
                this.$message.error(error.message);
                return false;
            });
        },
        handleFriend(friend) {
            this.$confirm('确定添加对方位好友吗?', '提示', {
                distinguishCancelAndClose: true,
                confirmButtonText: '确定',
                cancelButtonText: '不加',
                //type: 'warning'
            }).then(() => {
                this.sendFriendHandle(friend, 1);
            }).catch(action => {
                if (action === 'cancel') {
                    this.sendFriendHandle(friend, 2);
                }
            });
        },
        freshApplyList(friend) {
            let newList = [];
            this.applyList.forEach((val, index) => {
                if (val.user_name !== friend.user_name) {
                    newList.push(val);
                }
            });
            this.applyList = newList;
        },
        sendFriendHandle(friend, desc) {
            let _this = this;
            axios.post('/api/user/handleFriend', {
                access_token: this.access_token,
                desc: desc,
                target: friend.from,
                //uid: friend.uid,
            }).then(res => {
                if (res.data.code === 1) {
                    this.$message.error(res.data.message);
                    return false;
                }

                this.$message.success({
                    message: res.data.message,
                    onClose: () => {
                        _this.freshApplyList(friend)
                        _this.getFriendList();
                    }
                });
                return false;
            }).catch(error => {
                this.$message.error(error.message);
                return false;
            });
        },
        getUserInfo() {
            axios.get('/api/user/info', {
                params: {access_token: this.access_token}
            }).then(res => {
                if (res.data.code === 1) {
                    this.$message.error(res.data.message);
                    return false;
                }

                this.setUserInfo(res.data.content);
                return false;
            }).catch(error => {
                this.$message.error(error.message);
                return false;
            });
        },
        setUserInfo(obj) {
            this.userInfo = obj;
            localStorage.setItem('userInfo', JSON.stringify(obj));
        },
        getFriendList(callback = function (){}) {
            axios.get('/api/user/friendList', {
                params: {access_token: this.access_token}
            }).then(res => {
                if (res.data.code === 1) {
                    this.$message.error(res.data.message);
                    return false;
                }

                this.friendList = res.data.content;
                if(callback) {
                    callback();
                }
            }).catch(error => {
                this.$message.error(error.message);
                return false;
            });
        },
        relink() {
            let _this = this;
            if (this.lock === true) {
                return false;
            }
            this.lock = true;
            setTimeout(function () {
                _this.link();
                _this.lock = false;
            }, 1000);
        },
        closeChat() {
            this.chatRoomDialogVisible = false;
        },
    },
    created() {
        this.init();
    }
});
